package studio.raptor.dispatcher.server.service;

import java.sql.Timestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import studio.raptor.databus.command.EventMetaData;
import studio.raptor.dispatcher.common.constant.EventStatus;
import studio.raptor.dispatcher.server.dao.EventDao;
import studio.raptor.dispatcher.server.entity.EventTrace;

/**
 * @author jack
 * @since 1.0
 */
@Service
public class EventService {

  private static final Logger log = LoggerFactory.getLogger(EventService.class);

  @Autowired
  EventDao eventDao;

  /**
   * 保存事件发送记录
   *
   * @param code 接口编码
   * @param kindId 事件种类id
   * @param eventType 事件类型 1：停复机，0：普通业务
   * @param traceId 事件id
   * @param metaData 事件元信息
   * @return true:保存成功，false：保存失败
   */
  public boolean saveEventTrace(String code, Integer kindId, Integer eventType, Long traceId,
      EventMetaData metaData) {
    log.debug("consumer:[{}],save event[{}]", code, metaData.getBusinessNo());
    EventTrace eventTrace = buildEventTrace(code, kindId, eventType, traceId, metaData);
    int result = eventDao.insertEventTrace(eventTrace);
    return result > 0 ? true : false;
  }


  /**
   * 更新事件发送记录.
   *
   * @param code 接口编码
   * @param kindId 事件种类编码
   * @param objectKey 订单id
   * @param status 事件最新状态
   * @param respCode 响应编码
   * @param respMsg 响应消息
   * @return true：更新成功，false：更新失败
   */
  public boolean updateEventTrace(String code, String objectKey, Integer kindId, String status,
      int respCode,
      String respMsg) {
    Timestamp timestamp = new Timestamp(System.currentTimeMillis());
    int result = eventDao
        .updateEventStatus(objectKey, kindId, code, status, timestamp, respCode, respMsg);
    return result > 0 ? true : false;
  }

  public boolean updateEventTrace(EventTrace eventTrace) {
    Timestamp timestamp = new Timestamp(System.currentTimeMillis());
    eventTrace.setLastUpdateDate(timestamp);
    int result = eventDao.updateEventStatus(eventTrace);
    return result > 0 ? true : false;
  }


  private EventTrace buildEventTrace(String code, Integer kindId, Integer eventType, Long traceId,
      EventMetaData metaData) {
    Timestamp timestamp = new Timestamp(System.currentTimeMillis());
    EventTrace eventTrace = new EventTrace();
    eventTrace.setCode(code);
    eventTrace.setKindId(kindId);
    eventTrace.setEventType(eventType);
    eventTrace.setTraceId(traceId);
    eventTrace.setObjectKey(metaData.getBusinessNo());
    eventTrace.setStatus(EventStatus.WAITED);
    eventTrace.setCreateDate(timestamp);
    eventTrace.setLastUpdateDate(timestamp);
    return eventTrace;
  }

}
